<?php

class Pay extends MX_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->lang->load('error', $this->public_model->getLanguage());
    }

    function showInfoPlayer()
    {
        $CI = &get_instance();
        $CI->load->model('game/game_model');
        $player_id = $this->session->userdata('id');
        $data = array();
        $data['username'] = $this->session->userdata('fullname');
        $data['player_acc_detail'] = $CI->game_model->getPlayer($player_id);
        $this->load->view('player_view', $data);
    }
    function menu()
    {
        $data= array();
        $menu = $this->uri->segment(2);
        
        $menuExchange = '';
        if ($menu == 'pointExchange')
            $menuExchange = 'Point';
            
        elseif ($menu == 'coinExchange')
            $menuExchange = 'Coin';
            
        elseif($menu == 'moneyExchange')
            $menuExchange = 'Money';
        
        $data['menuExchange'] = $menuExchange;
        $this->load->view('menu_view', $data);
    }
    function moneyExchange()
    {
        if (!modules::run('login/is_user_logged_in'))
        {
            redirect('/login');
			return;   
        }
        //get info
        $player_id = $this->session->userdata('id');
        $this->load->model('pay_model');
        $CI = &get_instance();
        $CI->load->model('game/game_model');
        $this->load->library('payment');
        
        $data = array();
        
        $data['menu'] = modules::run('pay/menu');
        $data['point_exchange'] = $this->pay_model->getPointExchange();
        $data['player_acc_detail'] = $CI->game_model->getPlayer($player_id);
        $data['countries'] = $this->pay_model->getCountries();
        if (count($data['countries']) > 0)
            $data['states'] = $this->pay_model->getStates($data['countries'][0]->id);    
        
        $data['paymentAccounts'] = $this->pay_model->getPaymentAccounts($player_id);
        if (count($data['paymentAccounts']) > 0)
        {
            $data['paymenttransactions'] = array();
            for ($i = 0; $i<count($data['paymentAccounts']); $i++)
                array_push($data['paymenttransactions'],$this->pay_model->getPaymenttransactions($data['paymentAccounts'][$i]->payment_account_id));
            $data['address'] = $this->pay_model->getAddress($data['paymentAccounts'][0]->address_id);
                
        }
            
         
        $action = $this->input->post('action');
        
        if ($action != null)
        {
            $money = $this->input->post('money');
            $Point = $money;
            $index = -1;
            //cal Points
            for($i = 0; $i< count($data['point_exchange']); $i++){
                if (($data['point_exchange'][$i]->money_amount) > ($money))
                {
                    $index = $i-1;
                    break;
                }
                else if (($data['point_exchange'][$i]->money_amount) == ($money))
                {
                    $index = $i;
                break;
                }
                else if (count($data['point_exchange']) == $i+1 && ($money) > ($data['point_exchange'][$i]->money_amount))
                {
                    $index = $i;
                    break;
                }
            }
            if ($index == -1)
            {
                //get value index 0
                if (count($data['point_exchange']) == 0)
                {
                    //no exchange
                    $Point = $money; 
                }
                else
                {
                    //exchange
                    $point_sys = $data['point_exchange'][0]->point;
                    $money_sys = $data['point_exchange'][0]->money_amount;
                    $Point = $money * $point_sys / $money_sys;
                }
            }
            else 
            {
                //get value last
                $point_sys = $data['point_exchange'][$index]->point;
                $money_sys = $data['point_exchange'][$index]->money_amount;
                $Point = $money * $point_sys / $money_sys;
            }
            $Point = (int)$Point;
            
            //before update, process credit card
            $data_cc = array();
            $data_cc['option_payment'] = $this->input->post('option_payment');
            if ($data_cc['option_payment'] == 'new')
            {
                //payment account
                $data_cc['cardType'] = $this->input->post('createPaymentCardType');
                $data_cc['cardName'] = $this->input->post('createPaymentName');
                $data_cc['cardNumber'] = $this->input->post('createPaymentNumber');
                $data_cc['cardCVV'] = $this->input->post('createPaymentCVV2Code');
                $data_cc['cardExpireMonth'] = $this->input->post('createPaymentExpireMonth');
                $data_cc['cardExpireYear'] = $this->input->post('createPaymentExpireYear');
                $data_cc['cardSave'] = $this->input->post('saveCreditCard');
                //address
                $data_cc['paymentAddress1'] = $this->input->post('createPaymentBillAddress1');
                $data_cc['paymentAddress2'] = $this->input->post('createPaymentBillAddress2');
                $data_cc['paymentCountry'] = $this->input->post('createPaymentBillCountry');
                $data_cc['paymentHasState'] = $this->input->post('createPaymentHasState');
                $data_cc['paymentBillCity'] = $this->input->post('createPaymentBillCity');
                $data_cc['paymentBillState'] = $this->input->post('createPaymentBillState');
                $data_cc['paymentBillStateText'] = $this->input->post('createPaymentBillStateText');
                $data_cc['paymentHasState'] = $this->input->post('createPaymentHasState');
                $data_cc['paymentBillZip'] = $this->input->post('createPaymentBillZip');
                $data_cc['paymentBillPhone1'] = $this->input->post('createPaymentBillPhone1');
                $data_cc['paymentBillPhone2'] = $this->input->post('createPaymentBillPhone2');
                $data_cc['paymentBillPhone3'] = $this->input->post('createPaymentBillPhone3');
                
                //phan tich name
                $arr_temp=array();
                $arr_temp=explode(' ',$data_cc['cardName']);
                $first_name='';
                $last_name='';
					if(count($arr_temp)>0){
						for($i=0;$i<count($arr_temp)-1;$i++){
							$first_name=$first_name.$arr_temp[$i] . ' ';
						}
						if($first_name!=''){
							$first_name=substr($first_name,0,-1);
						}else{
							$first_name=$arr_temp[0];
						}
						if(count($arr_temp)>1){
							$last_name=$arr_temp[count($arr_temp)-1];
						}else{
							$last_name='';
						}
					}else{
						$first_name=$this->input->post('paymentName');
						$last_name='';
					}
                //$this->payment->makePayment()    
                //saving payment account
                $creditCardInfo = array('cardNum' => $this->payment->encrypt($data_cc['cardNumber'] ),
							'creditCardLast4Digits'=>substr($data_cc['cardNumber'] ,strlen($data_cc['cardNumber'] )-4,4),
							'expYear' => $data_cc['cardExpireYear'],
							'expMonth' => $data_cc['cardExpireMonth'],
							'cardCodePresent' => 'ValuePresent',
							'cardCode' => $data_cc['cardCVV'], 
							'cardholderFirstName' => $first_name,
							'cardholderLastName' => $last_name,
							'cardHolderCompanyName' => null,
							'cardHolderFullName' => $first_name. " ". $last_name,																
							'track1' => null,
							'track2' => null,
							'streetAddressLine1' => $data_cc['paymentAddress1'],
							'zip' => $data_cc['paymentBillZip'],
							'ext' => (isset($zipcode[1])?$zipcode[1]:""),									
							'cardType' => $data_cc['cardType'], 
							'entryMode' => 'Manual',
							'signature' => null,
							'cardPresent' => 'NO',								
                );
                $options = array(
                    'clientRequestNumber' => 'no',
                    'useTestMode' => 'yes',
                    'amount' => $money,
                );
            }
            else    //old_payment_account
            {
                
            }
            
            //update balance player
            $data_update_player = array();
            $data_update_player['point_balance'] = (int)$data['player_acc_detail']->point_balance + (int)$Point;
            $this->db->where('id', $player_id);
            $this->db->update('player', $data_update_player);
            
            //insert playerpaymenthistory
            $data_insert_pph = array();
            $data_insert_pph['player_id'] = $data['player_acc_detail']->id;
            $data_insert_pph['amount'] = $money;
            $data_insert_pph['paytype'] = "+";
            $data_insert_pph['description'] = "Buy points";
            $data_insert_pph['point'] = $Point;
            $this->db->insert('playerpaymenthistory', $data_insert_pph);
            
            $data['BuyResult'] = true;
            $data['BuyMessage'] = 'Buy '.$Point . ' points success';
        }
        $data['showInfoPlayer'] = modules::run('pay/showInfoPlayer');
        $content = $this->load->view('moneyExchange_view', $data, true);
        Template::display($content);
    }
    function pointExchange($game_id = null)
    {
        if (!modules::run('login/is_user_logged_in'))
        {
            redirect('/login');
			return;   
        }
        $data = array();
        $data['showInfoPlayer'] = modules::run('pay/showInfoPlayer');
        $data['menu'] = modules::run('pay/menu');
        $this->load->helper('game_api.php');
        $CI = &get_instance();
        $CI->load->model('game/game_model');
        $player_id = $this->session->userdata('id');
        $data['player_acc_detail'] = $CI->game_model->getPlayer($player_id);
        $data['game_players'] = $CI->game_model->getGamePlayer(null, $player_id);
        $rss = array();
        for ($i = 0; $i < count($data['game_players']); $i++)
        {
            $rs = array();
            $games_id = $data['game_players'][$i]->game_id;
            $games_detail = $CI->game_model->getGameDetail($games_id);
            //info game
            $rs['id'] = $games_id;
            $rs['name'] = $games_detail->name;
            array_push($rss, $rs);
        }
        $data['games_detail'] = $rss;

        if ($game_id != null)
        {
            $data['game_id'] = $game_id;
            $data['game_player'] = $CI->game_model->getGamePlayer($game_id, $player_id);
            $data['coin_exchange'] = $CI->game_model->getCoinExchange($game_id);
            $data['game_detail'] = $CI->game_model->getGameDetail($game_id);

            $params_url = "&Player=" . urlencode($data['game_player']->player_username);
            $api = games_api_getPlayerInfo($data['game_detail']->game_brand_param, $params_url);
            if ($api['Result'] == 'Ok')
            {
                $data['game_player']->coin_balance = (int)$api['Balance'] + (int)$api['RingChips'] + (int)
                    $api['RegChips'];
            }
        }
        $PutResult = $this->session->userdata('PutCoinsResult');
        $this->session->unset_userdata('PutCoinsResult');

        if (isset($PutResult) && strtoupper($PutResult) == strtoupper('Error'))
        {
            $data['PutResult'] = false;
            $data['PutMessage'] = $this->session->userdata('PutCoinsMessage');
            if (empty($data['PutMessage']))
            {
                $data['PutMessage'] = 'Put coins error'; //nap tien that bai
            }
            $this->session->unset_userdata('PutCoinsMessage');
        } else
            if (isset($PutResult) && strtoupper($PutResult) == strtoupper('Ok'))
            {
                $data['PutResult'] = true;
                $data['PutMessage'] = $this->session->userdata('PutCoinsMessage');
                if (empty($data['PutMessage']))
                {
                    $data['PutMessage'] = 'Put coins success'; //nap tien that bai
                }
                $this->session->unset_userdata('PutCoinsMessage');
            }
        $content = $this->load->view('pointExchange_view', $data, true);
        Template::display($content);
    }
    function coinExchange($game_id = null)
    {
        if (!modules::run('login/is_user_logged_in'))
        {
            redirect('/login');
			return;   
        }
        $data = array();
        $data['showInfoPlayer'] = modules::run('pay/showInfoPlayer');
        $data['menu'] = modules::run('pay/menu');
        $this->load->helper('game_api.php');
        $CI = &get_instance();
        $CI->load->model('game/game_model');
        $player_id = $this->session->userdata('id');
        $data['player_acc_detail'] = $CI->game_model->getPlayer($player_id);
        $data['game_players'] = $CI->game_model->getGamePlayer(null, $player_id);
        $rss = array();
        for ($i = 0; $i < count($data['game_players']); $i++)
        {
            $rs = array();
            $games_id = $data['game_players'][$i]->game_id;
            $games_detail = $CI->game_model->getGameDetail($games_id);
            //info game
            $rs['id'] = $games_id;
            $rs['name'] = $games_detail->name;
            array_push($rss, $rs);
        }
        $data['games_detail'] = $rss;

        if ($game_id != null)
        {
            $data['game_id'] = $game_id;
            $data['game_player'] = $CI->game_model->getGamePlayer($game_id, $player_id);
            $data['coin_exchange'] = $CI->game_model->getCoinExchange($game_id);
            $data['game_detail'] = $CI->game_model->getGameDetail($game_id);

            $params_url = "&Player=" . urlencode($data['game_player']->player_username);
            $api = games_api_getPlayerInfo($data['game_detail']->game_brand_param, $params_url);
            if ($api['Result'] == 'Ok')
            {
                $data['game_player']->coin_balance = (int)$api['Balance'] + (int)$api['RingChips'] + (int)
                    $api['RegChips'];
            }
        }
        $GetResult = $this->session->userdata('GetPointsResult');
        $this->session->unset_userdata('GetPointsResult');

        if (isset($GetResult) && strtoupper($GetResult) == strtoupper('Error'))
        {
            $data['GetResult'] = false;
            $data['GetMessage'] = $this->session->userdata('GetPointsMessage');
            if (empty($data['GetMessage']))
            {
                $data['GetMessage'] = 'Get error: pay.php 150'; //lay tien that bai
            }
            $this->session->unset_userdata('GetPointsMessage');
        } else
            if (isset($GetResult) && strtoupper($GetResult) == strtoupper('Ok'))
            {
                $data['GetResult'] = true;
                $data['GetMessage'] = 'Get successful: pay.php 78'; //lay tien thanh cong
            }
        $content = $this->load->view('coinExchange_view', $data, true);
        Template::display($content);
    }
    function index()
    {
        //$is_logged_in = $this->session->userdata('is_logged_in');
        
        if (!modules::run('login/is_user_logged_in'))
        {
            redirect('/login');
			return;   
        }
        $data = array();
        $data['showInfoPlayer'] = modules::run('pay/showInfoPlayer');
        $data['menu'] = modules::run('pay/menu');
        $content = $this->load->view('pay_view', $data, true);
        Template::display($content);
    }
    function money_point_history($ipage = null)
    {
        if (!modules::run('login/is_user_logged_in'))
        {
            redirect('/login');
			return;   
        }
        
        $numRecord = $this->config->item('numRecord');  
        
        $CI = &get_instance();
        $CI->load->model('game/game_model');
        $this->load->model('pay_model');
        $data = array();
        $player_id = $this->session->userdata('id');
        $data['player_acc_detail'] = $CI->game_model->getPlayer($player_id);
        if ($ipage == null)
            $ipage = 1;
        $startRecord = ($ipage-1) * $numRecord;
        $data['player_payment_history'] = $this->pay_model->getPlayerPaymentHistory($player_id, $startRecord , $numRecord);
        $data['countRowHistory'] = $this->pay_model->getCount_PlayerPaymentHistory($player_id);
        $data['ipage'] = $ipage;
        $data['startRecord'] = $startRecord;
        $data['countPage'] = $data['countRowHistory'] / $numRecord;
        
        if ($ipage != 1)
        {
            $this->load->view('money_point_history_view', $data);
        }
        else
        {
            $content = $this->load->view('money_point_history_view', $data, true);
            Template::display($content);    
        } 
        
    }
    
    function ajax_getStatesByCountryId($country_id = null)
    {
        if ($country_id != null)
        {
            $this->load->model('pay_model');
            $states = $this->pay_model->getStates($country_id);   
            $html = "";
            
            foreach($states as $state){
                $html .= "<option value='$state->id'>$state->name</option>";                                
            } 
            echo $html; 
        }
    }
}
